package com.example.http;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author ：wuhong-016
 * @version v1.0.0
 * @Create : 2021/1/27 13:42
 * @Description : TODO
 **/
public class TestHttp {


    public static void main(String[] args) {
        System.out.println("111");
    }


    public static void main1(String[] args) throws InterruptedException {


        Runnable taskTemp = new Runnable() {


            private int iCounter;


            @Override
            public void run() {
                // 发起请求
                iCounter++;
                System.out.println(System.nanoTime() + " [" + Thread.currentThread().getName() + "] iCounter = " + iCounter);
            }
        };


        TestHttp latchTest = new TestHttp();
        latchTest.startNThreadsByBarrier(5, taskTemp);
    }


    public void startNThreadsByBarrier(int threadNums, Runnable finishTask) throws InterruptedException {
        // 设置栅栏解除时的动作，比如初始化某些值
        CyclicBarrier barrier = new CyclicBarrier(threadNums, finishTask);
        // 启动 n 个线程，与栅栏阀值一致，即当线程准备数达到要求时，栅栏刚好开启，从而达到统一控制效果
        for (int i = 0; i < threadNums; i++) {
            Thread.sleep(100);
            new Thread(new CounterTask(barrier)).start();
        }
        System.out.println(Thread.currentThread().getName() + " out over...");
    }

    public static String long2short() {
        String url = "https://cxwx-dev.cpic.com.cn/CPICDISPATCH/servlet/SupInf?method=long2short&fromUser=gh_60e60d160cfb";
        String param = "{\"action\":\"long2short\",\"long_url\":\"https://wxcd.cpic.com.cn/cx-wechat/#/home?param=6nSoDsCvy4aoiam%2FDZ07XiP48kpftymABRIH8izyrO%2Fw4ITbY4Kxnp%2B%2BOSeZmEdVLK4azkcyK0Eyd3ShnZnBLg6ySbD%2BZQXEkIX2exWaf3KiMCuvuq3bQCukyTkzy3OU&branch=%7B%7BbranchCode%7D%7D\"}";
        return HttpUtil.sendByPost(url, param, "UTF-8");
    }
}


class CounterTask implements Runnable {


    private CyclicBarrier barrier;


    public CounterTask(final CyclicBarrier barrier) {
        this.barrier = barrier;
    }


    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " - " + System.currentTimeMillis() + " is ready...");
        try {
            // 设置栅栏，使在此等待，到达位置的线程达到要求即可开启大门
            barrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " - " + System.currentTimeMillis() + " started...");
        String token = TestHttp.long2short();
        if (null != token) {
            System.out.println(Thread.currentThread().getName() + " - 获取到token - " + token);
        } else {
            System.out.println(Thread.currentThread().getName() + " - 未获取到token - " + token);
        }
    }


}

